package com.example.front.controller;

import com.example.common.dto.JsonResult;
import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.front.dto.*;
import com.example.front.entity.Gateway;
import com.example.front.mapper.IncidentMapper;
import com.example.front.serivce.GatewayService;
import com.example.front.serivce.IncidentService;
import com.example.front.until.IsStr;
import com.example.front.until.TtsTool;
import com.example.interceptor.UserContext;
import com.example.passport.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.UUID;

@Api(tags = "事件记录管理")
@RestController
@CrossOrigin
@RequestMapping("/front/incident")
public class IncidentController {

    @Autowired
    ObjectMapper objectMapper;
    @Resource
    IncidentService incidentService;
    @Resource
    IncidentMapper incidentMapper;
    @Resource
    GatewayService gatewayService;


    @Value("${com.sun.yuyinFilePath}")
    private String yuyinFilePath;


    @ApiOperation("添加事件记录")
    @PostMapping("/create")
    public JsonResult<String> create(@RequestBody String raw) throws Exception {
        System.out.println(raw);
        BoxRequest demoRequest = objectMapper.readValue(raw, BoxRequest.class);
        IncidentCreateDto incidentCreateDto = new IncidentCreateDto();
        BeanUtils.copyProperties(demoRequest, incidentCreateDto);
//        Gateway gateway = gatewayService.findByCode(incidentCreateDto.getCode());
//        incidentCreateDto.setTenantId(gateway.getTenantId());
//{"ID":"9239504622173178948", "model":"SP-AD433A", "dev_addr":38, "key_num":1, "key_sta":1}
        //按钮盒按键第一次提交事件
        if (incidentCreateDto.getKeySta() == 1) {
            NoticeDto noticeDto = incidentService.create(incidentCreateDto);

            if (noticeDto != null && noticeDto.getUser() != null) {
                String str = "";
                //如果设备为空 报工艺名称
                //当维修班组名称全英文时 用,隔开

                if ("".equals(noticeDto.getEquName()) || noticeDto.getEquName() == null) {

                    if (noticeDto.getMaintenanceName() != null && !"".equals(noticeDto.getMaintenanceName())) {
                        if (IsStr.isStr(noticeDto.getMaintenanceName())) {
                            String maintenanceName = noticeDto.getMaintenanceName();
                            String[] split = maintenanceName.split("");
                            noticeDto.setMaintenanceName(StringUtils.join(split, " , "));
                        }
                    }

                    str = noticeDto.getMaintenanceName() + "," + noticeDto.getLineName() + "," + noticeDto.getCraftName() + ", 呼叫 ," + noticeDto.getEventName();
                } else {

                    if (noticeDto.getMaintainGroup() != null && !"".equals(noticeDto.getMaintainGroup())) {
                        if (IsStr.isStr(noticeDto.getMaintainGroup())) {
                            String maintenanceName = noticeDto.getMaintainGroup();
                            String[] split = maintenanceName.split("");
                            noticeDto.setMaintenanceName(StringUtils.join(split, " , "));
                        }
                    }

                    str = noticeDto.getMaintainGroup() + "," + noticeDto.getEquName() + "," + noticeDto.getEquNum() + ", 呼叫 ," + noticeDto.getEventName();
                }

                //通过tts语音包生成语音文件
//                TtsTool ttsTool = new TtsTool(yuyinFilePath);
//                String uuid = UUID.randomUUID().toString().replace("-", "");
//                ttsTool.textToVoice("请注意, " + str + " ,呼叫", uuid);
                IncidentDto incidentDto = new IncidentDto();
                incidentDto.setId(noticeDto.getId());
                incidentDto.setText("请注意, " + str);
                incidentMapper.updateText(incidentDto);
                for (User user : noticeDto.getUser()) {
                    incidentService.notice(str, user, noticeDto.getLevelId());
                }
            }
//            incidentService.startResponse(incidentCreateDto);
            return new JsonResult<>();
        }
        if (incidentCreateDto.getKeySta() == 2) {
            incidentService.startResponse(incidentCreateDto);
            return new JsonResult<>();
        }
        if (incidentCreateDto.getKeySta() == 0) {
            incidentService.finish(incidentCreateDto);
            return new JsonResult<>();
        }
        return new JsonResult<>(false, "添加失败");
    }

    @ApiOperation("消息推送")
    @GetMapping("/pushMessage")
    public void pushMessage() throws Exception {
        incidentService.pushMessage();
    }

    @ApiOperation("列出事件记录列表")
    @GetMapping("/list")
    public JsonResult<ListDto<IncidentDto>> list(IncidentSearchDto condition, Pagination pagination) {
        condition.setTenantId(UserContext.getUser().getTenantId());
        ListDto<IncidentDto> incidentDtoList = incidentService.listIncident(condition, pagination);

        return new JsonResult<>(incidentDtoList);
    }

    @ApiOperation("修改事件记录")
    @PostMapping("/update")
    public JsonResult<String> update(@Valid IncidentDto incidentDto) {
        System.out.println(incidentDto);
        User user = UserContext.getUser();
        incidentDto.setTenantId(user.getTenantId());
        incidentService.update(incidentDto);
        return new JsonResult<>();
    }

    @ApiOperation("删除事件记录")
    @PostMapping("/delete")
    public JsonResult<String> delete(long id) {
        incidentService.deleteById(id);
        return new JsonResult<>();
    }

    @ApiOperation("获取当前登录的用户")
    @GetMapping("/huoqu")
    public JsonResult<String> huoqu(String code) {

        return new JsonResult<>();
    }
}
